import Moon from '../moon'
import { formatDataToUrl } from '../util/wx-mini';
export default function initPuv() {
  const _Page = Page;
  const _App = App;
  const _Component = Component;
  (App as any) = function (options) {
    // onLaunch
    let _funs = options.onLaunch;
    options.onLaunch = function (object) {
      _funs && _funs.apply(this, [object]);
      try {
        Moon.logger({
          t: 'app',
          pageurl: formatDataToUrl(object.path, object.query),
          scene: object.scene
        })
      } catch (e) {
        console.error('wx-moon app:', e);
      }
    }
    return _App(options);
  }

  // 延长1.5秒，防止快速跳转页面算入统计量
  const delayTime = 1200;
  let delayObj;

  const onShow = function() {
    try {
      delayObj && clearTimeout(delayObj)
      delayObj = setTimeout(() => {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        let data = {
          t: 'pu',
          pageurl: formatDataToUrl(currentPage.route, currentPage.options),
        }
        if(currentPage.options.logtype){
          currentPage.options.area = currentPage.options.logtype;
          delete currentPage.options.logtype;
          data = {
            ...data,
            ...currentPage.options
          }
        }
        Moon.logger(data)
      }, delayTime);
    } catch (e) {
      console.error('wx-moon puv:', e);
    }
  };

  (Page as any) = function (options) {
    let _funs = options.onShow;
    options.onShow = function () {
      _funs && _funs.apply(this, []);
      onShow();
    }
    return _Page(options);
  };

  (Component as any) = function (options) {
    if (!options.methods) options.methods = {};
    let _funs = options.methods.onShow;
    options.methods.onShow = function () {
      _funs && _funs.apply(this, []);
      onShow();
    }
    return _Component(options);
  }
}